package com.tarry.shop.search.mq.listener;

import com.rabbitmq.client.Channel;
import com.tarry.shop.constant.RabbitMQConstant;
import com.tarry.shop.goods.entity.Goods;
import com.tarry.shop.search.domain.dto.GoodsDTO;
import com.tarry.shop.search.service.GoodsSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

import java.io.IOException;

/**
 *  商品信息监听器
 */
@Configuration
@Slf4j
public class GoodsQueueListener {

    @Autowired
    private GoodsSearchService goodsSearchService;

    /**
     *  监听MQ消息，将商品信息添加到ES中
     * @param goods
     * @param channel
     * @param message
     */
    @RabbitListener(queues = RabbitMQConstant.GOODS_QUEUE)
    public void addGoodsToES(Goods goods, Channel channel, Message message){
        log.info("goods: {}",goods);
        try {
            GoodsDTO goodsDTO = new GoodsDTO();
            BeanUtils.copyProperties(goods,goodsDTO);
            log.info("goods {}",goodsDTO);
            goodsSearchService.save(goodsDTO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
